package com.example.administrator.ksf_zty.MaterialActivity;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

import com.example.administrator.ksf_zty.JavaModels.BarcodeModel;
import com.example.administrator.ksf_zty.JavaModels.MaterialBLModel;
import com.example.administrator.ksf_zty.R;
import com.example.administrator.ksf_zty.util.BaseActivity;
import com.example.administrator.ksf_zty.util.Config;
import com.example.administrator.ksf_zty.util.HttpUtil;
import com.example.administrator.ksf_zty.util.SQLiteHelper;
import com.example.administrator.ksf_zty.util.Tips;
import com.example.administrator.ksf_zty.util.TitleUtils;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.example.administrator.ksf_zty.util.HttpUtils.StrHttp_URLGetZBBarCode;
import static com.example.administrator.ksf_zty.util.HttpUtils.StrHttp_URLZ_TRCE_H_DOWNLOAD_RESERVATION_PDA;

public class MaterialBackActivity extends BaseActivity {

    ImageButton back;
    Button titleButton;

    EditText txtBLCode;
    EditText txtBarcode;
    EditText txtDoucno;
    EditText txtQty;
    EditText txtName;
    EditText txtPC;
    private static SQLiteDatabase sqLiteDatabase;

    private String strBLCode = "";//单据号码
    private BarcodeModel barcodeModel;
    private String strStock = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_material_back);

        txtBLCode = (EditText) findViewById(R.id.MaterialBack_txtBLCode);
        txtBarcode = (EditText) findViewById(R.id.MaterialBack_txtBarcode);
        txtDoucno = (EditText) findViewById(R.id.MaterialBack_txtDoucno);
        txtQty = (EditText) findViewById(R.id.MaterialBack_txtQty);
        txtName = (EditText) findViewById(R.id.MaterialBack_txtName);
        txtPC = (EditText) findViewById(R.id.MaterialBack_txtPC);
        SQLiteOpenHelper helper = new SQLiteHelper(MaterialBackActivity.this, Config.DataBaseName, null, 1);
        sqLiteDatabase = helper.getWritableDatabase();
        SetTitle();
        SetOnClick();
        SetEditTextClick();//文本框回车事件
    }

    //给按钮设置事件
    private void SetOnClick() {
        //保存按钮
        Button btnSave = (Button) findViewById(R.id.MaterialBack_btnSave);
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        //查询详情按钮
        Button btnSel = (Button) findViewById(R.id.MaterialBack_btnSel);
        btnSel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MaterialBackActivity.this, MaterialBackDetailsActivity.class);
                intent.putExtra("name", "");//传参数
                startActivity(intent);
            }
        });
        //提交按钮
        Button btnSubmit = (Button) findViewById(R.id.MaterialBack_btnSubmit);
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        //返回按钮
        Button btnCancel = (Button) findViewById(R.id.MaterialBack_btnCancel);
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MaterialBackActivity.this, MaterialMenuActivity.class);
                intent.putExtra("name", "");//传参数
                startActivity(intent);
            }
        });
    }

    //文本框回车事件
    private void SetEditTextClick() {
        Log.d("Page", "SetEditTextClick成功！");
        //输入单号，监听回车键
        txtBLCode.setOnKeyListener(new View.OnKeyListener() {
            @TargetApi(Build.VERSION_CODES.CUPCAKE)
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    Log.d("lhd", "按下的按键为：" + keyCode);
                    //隐藏软键盘
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                    strBLCode = txtBLCode.getText().toString().trim().replace(" ", "").toUpperCase();//去空格
                    txtBLCode.setText(strBLCode);
                    GetDoucno(strBLCode);
                    return true;
                }
                return false;
            }
        });
        //输入栈板条码监听回车键
        txtBarcode.setOnKeyListener(new View.OnKeyListener() {
            @TargetApi(Build.VERSION_CODES.CUPCAKE)
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    Log.d("lhd", "按下的按键为：" + keyCode);
                    //隐藏软键盘
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                    String strBarcode = txtBarcode.getText().toString().trim().toUpperCase();//去空格
                    txtBarcode.setText(strBarcode);
                    GetBarCode(strBarcode);
                    return true;
                }
                return false;
            }
        });

        //输入数量监听回车键
        txtQty.setOnKeyListener(new View.OnKeyListener() {
            @TargetApi(Build.VERSION_CODES.CUPCAKE)
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    Log.d("lhd", "按下的按键为：" + keyCode);
                    //隐藏软键盘
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                    String strQty = txtQty.getText().toString().trim().toUpperCase();//去空格
                    txtQty.setText(strQty);
                    if (strQty.isEmpty()) {
                    }
                    SetbtnSave();
                    return true;
                }
                return false;
            }
        });
    }

    //下载SAP单据
    private void GetDoucno(final String doucno) {
        if ("".equals(doucno.trim())) {
            Tips.show(MaterialBackActivity.this, "单号不能为空", 1000);
            return;
        }

        //生产订单备料/退料信息读取接口程序
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("I_WERKS", Config.strI_WERKS);//作业工厂
        builder.add("I_ZSGNUM", doucno);//单号
        builder.add("I_AUFNR", "");//生产订单号
        builder.add("I_ZSGTYP", "R");//R:退料 P:生产

        RequestBody formBody = builder.build();
        Log.d("lhd", StrHttp_URLZ_TRCE_H_DOWNLOAD_RESERVATION_PDA);
        HttpUtil.sendOkHttpRequest(StrHttp_URLZ_TRCE_H_DOWNLOAD_RESERVATION_PDA, formBody, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("LOG111", "网络异常11");
                MaterialBackActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //这里的代码在主线程中执行
                        Tips.show(MaterialBackActivity.this, "网络异常11", 1000);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("LOG111", "成功");
                //解析数据
                final String responseData = response.body().string();
                Log.d("Json", responseData);
                try {
                    final JSONObject obj = new JSONObject(responseData);

                    if (obj.getString("success").equals("0")) {
                        Log.d("success", "成功,准备转换");
                        //给集合对象里面赋值
                        MaterialBLModel materialBLModel = new Gson().fromJson(responseData, MaterialBLModel.class);
                        Log.d("Model", "转换成功");
                        int strO_SUBRC = materialBLModel.getList().getO_SUBRC();
                        final String strO_ZMSG = materialBLModel.getList().getO_ZMSG();
                        if (strO_SUBRC != 0) {
                            //弹出提示框
                            MaterialBackActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    //这里的代码在主线程中执行
                                    Tips.show(MaterialBackActivity.this, strO_ZMSG, 1000);
                                }
                            });
                            return;
                        }
                        doucno.trim();
                        String strSqlDel = " Delete From MaterSap Where BLDH='" + doucno + "'";
                        Log.d("SQLInsert", "准备删除！" + strSqlDel);
                        sqLiteDatabase.execSQL(strSqlDel);
                        Log.d("SQLInsert", "删除成功！" + strSqlDel);
                        String I_VBELN = doucno;//单号
                        for (int i = 0; i < materialBLModel.getList().getOUTTAB().size(); i++) {
                            String strMATNR = materialBLModel.getList().getOUTTAB().get(i).getMATNR();//料号
                            String strAUFNR = materialBLModel.getList().getOUTTAB().get(i).getAUFNR();//生产订单号
                            String strMAKTX = materialBLModel.getList().getOUTTAB().get(i).getMAKTX();//物料描述
                            String strCHARG = materialBLModel.getList().getOUTTAB().get(i).getCHARG();//批次
                            double strLFIMG = materialBLModel.getList().getOUTTAB().get(i).getZSGMNG();//数量
                            String strLGORT = materialBLModel.getList().getOUTTAB().get(i).getLGORT();//库位
                            String strWERKS = materialBLModel.getList().getOUTTAB().get(i).getWERKS();//工厂代码
                            String strMEINS = materialBLModel.getList().getOUTTAB().get(i).getMEINS();//单位
                            String strSqlInSert = "insert into MaterSap(I_WERKS,Stock,BLDH,DDH,Code,Name,PC,DW,Qty,Kind) values " +
                                    "('" + strWERKS + "','" + strLGORT + "','" + I_VBELN + "','" + strAUFNR + "','" + strMATNR + "','" + strMAKTX + "'," +
                                    "'" + strCHARG + "','" + strMEINS + "'," + strLFIMG + ",'退库')";
                            sqLiteDatabase.execSQL(strSqlInSert);
                            Log.d("SQLInsert", "插入数据成功！" + strSqlInSert);

                            strBLCode = doucno;//单据号码
                            //弹出提示框
                            MaterialBackActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    //这里的代码在主线程中执行
                                    //点击回车键后出现粘贴BUG，这里把焦点移动到数量上
                                    txtBarcode.setFocusable(true);
                                    txtBarcode.setFocusableInTouchMode(true);
                                    txtBarcode.requestFocus();
                                    txtBarcode.requestFocusFromTouch();
                                }
                            });
                            strStock = strLGORT;//单据仓库
                        }
                    } else {
                        MaterialBackActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //弹出提示框
                                //这里的代码在主线程中执行
                                Tips.show(MaterialBackActivity.this, "接口调用失败!", 1000);
                            }
                        });
                        return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //根据栈板条码获取栈板信息
    private void GetBarCode(String barcode) {
        if ("".equals(barcode.trim())) {
            Tips.show(MaterialBackActivity.this, "栈板条码不能为空!", 1000);
            return;
        }
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("I_WERKS", Config.strI_WERKS);
        builder.add("strBarcode", barcode);
        RequestBody formBody = builder.build();
        HttpUtil.sendOkHttpRequest(StrHttp_URLGetZBBarCode, formBody, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("LOG111", "网络异常11");
                MaterialBackActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //这里的代码在主线程中执行
                        Tips.show(MaterialBackActivity.this, "网络异常11", 1000);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("LOG111", "成功");
                //解析数据
                final String responseData = response.body().string();
                Log.d("Json", responseData);
                try {
                    final JSONObject obj = new JSONObject(responseData);

                    if (obj.getString("success").equals("0")) {
                        Log.d("success", "成功");
                        //给集合对象里面赋值
                        barcodeModel = new Gson().fromJson(responseData, BarcodeModel.class);
                        final String strBarcode = barcodeModel.getList().get(0).getBarcode();
                        final String strCode = barcodeModel.getList().get(0).getCode();
                        final String strName = barcodeModel.getList().get(0).getName();
                        final String strPC = barcodeModel.getList().get(0).getPC();
                        final double strQty = barcodeModel.getList().get(0).getQty();

                        MaterialBackActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                txtBarcode.setText(strBarcode);
                                txtName.setText(strName);
                                txtPC.setText(strPC);
                                txtQty.setText(String.valueOf(strQty));
                                txtQty.setFocusable(true);
                                txtQty.setFocusableInTouchMode(true);
                                txtQty.requestFocus();
                                txtQty.requestFocusFromTouch();
                            }
                        });
                    } else {
                        final String result = obj.getString("result").trim();
                        MaterialBackActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Tips.show(MaterialBackActivity.this, result, 1000);
                            }
                        });
                        return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //保存按钮
    private void SetbtnSave() {
        //将数据保存在本地数据库中
        final String strBarcode = barcodeModel.getList().get(0).getBarcode();//条码
        final String strCode = barcodeModel.getList().get(0).getCode();//料号
        final String strName = barcodeModel.getList().get(0).getName();//物料描述
        final String strPC = barcodeModel.getList().get(0).getPC();//批次
        final String strDW = barcodeModel.getList().get(0).getDW();//单位
        final String strQty = txtQty.getText().toString().trim();//扫描数量
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDateTime = simpleDateFormat.format(date);//当前时间
        String strDDH = "";
        String strSqlInSert = "Insert into Mater(I_WERKS,Stock,BLDH,DDH,Barcode,Code,Name,PC,DW,Qty,Kind,Uno,Odate) " +
                " values ('" + Config.strI_WERKS + "','" + strStock + "','" + strBLCode + "','" + strDDH + "','" + strBarcode + "','" + strCode + "'" +
                ",'" + strName + "','" + strPC + "','" + strDW + "'," + strQty + ",'退库','" + Config.StrUserCode + "','" + strDateTime + "')";
        Log.d("Insert", strSqlInSert);
        sqLiteDatabase.execSQL(strSqlInSert);
        Tips.show(MaterialBackActivity.this, "保存成功", 1000);
    }

    //设置Title
    private void SetTitle() {
        back = (ImageButton) findViewById(R.id.back);
        titleButton = (Button) findViewById(R.id.titleButton);
        //设置标题(第三个参数是标题文字，直接替换""内容即可，第五个参数是标题右边按钮文字，第六个参数是设置是否显示返回按钮)
        TitleUtils.setTitle(this, R.id.title_sys_set, "生产退料", this,
                "", true);
        //返回按钮事件
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }
}
